package com.wuyi.tea.interceptor;

import com.wuyi.tea.enums.ConstantEnum;
import com.wuyi.tea.util.JwtUtil;
import com.wuyi.tea.util.LocalStorageUtil;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor implements HandlerInterceptor {
//    @Autowired
//    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }

//        LocalStorageUtil.set(ConstantEnum.ADMIN_ID);
//        return true;

		//从请求头获取令牌
        String token=request.getHeader(JwtUtil.tokenName);
        try {
            //判断是否携带令牌
            if (StringUtils.isEmpty(token)){
                throw new Exception("未携带JWT令牌");
            }
            //判断令牌是否有效
            Claims claims = JwtUtil.parseJWT(token);
            if (claims==null){
                throw new Exception("JWT令牌有误");
            }

            LocalStorageUtil.set(claims.get("userId"));
        }catch (Exception e){
            //出现异常，拦截，设置状态码为401
            response.setStatus(401);
            throw new RuntimeException(e.getMessage());
        }
        return true;
    }
}